# -*- coding: utf-8 -*-

from __future__ import unicode_literals
import frappe
from frappe import _

def get_permission_query_conditions(user):
    """获取权限查询条件"""
    if not user:
        user = frappe.session.user
    
    # 系统管理员可以查看所有记录
    if "System Manager" in frappe.get_roles(user):
        return None
    
    # 余料管理员可以查看所有记录
    if "Scrap Manager" in frappe.get_roles(user):
        return None
    
    # 余料用户只能查看自己创建的记录或自己负责的仓库的记录
    if "Scrap User" in frappe.get_roles(user):
        # 获取用户负责的仓库
        user_warehouses = frappe.db.sql_list("""
            SELECT warehouse FROM `tabScrap Warehouse`
            WHERE responsible_user = %s
        """, user)
        
        if user_warehouses:
            return """(
                `tabScrap Transaction`.owner = {user}
                OR `tabScrap Transaction`.warehouse IN ({warehouses})
            )""".format(
                user=frappe.db.escape(user),
                warehouses=", ".join([f"'{w}'" for w in user_warehouses])
            )
        else:
            return """`tabScrap Transaction`.owner = {user}""".format(
                user=frappe.db.escape(user)
            )
    
    # 其他角色只能查看自己创建的记录
    return """`tabScrap Transaction`.owner = {user}""".format(
        user=frappe.db.escape(user)
    )

def has_permission(doc, ptype, user):
    """检查用户是否有权限访问文档"""
    if not user:
        user = frappe.session.user
    
    # 系统管理员有所有权限
    if "System Manager" in frappe.get_roles(user):
        return True
    
    # 余料管理员有所有权限
    if "Scrap Manager" in frappe.get_roles(user):
        return True
    
    # 余料用户可以创建、读取自己创建的记录或自己负责的仓库的记录
    if "Scrap User" in frappe.get_roles(user):
        if ptype in ("read", "write", "create"):
            # 检查是否是用户负责的仓库
            user_warehouses = frappe.db.sql_list("""
                SELECT warehouse FROM `tabScrap Warehouse`
                WHERE responsible_user = %s
            """, user)
            
            if doc.warehouse in user_warehouses:
                return True
            
            # 检查是否是自己创建的记录
            if doc.owner == user:
                return True
            
            return False
        elif ptype == "submit":
            # 余料用户可以提交自己负责的仓库的记录
            user_warehouses = frappe.db.sql_list("""
                SELECT warehouse FROM `tabScrap Warehouse`
                WHERE responsible_user = %s
            """, user)
            
            if doc.warehouse in user_warehouses:
                return True
            
            return False
        elif ptype == "cancel":
            # 余料用户可以取消自己负责的仓库的记录
            user_warehouses = frappe.db.sql_list("""
                SELECT warehouse FROM `tabScrap Warehouse`
                WHERE responsible_user = %s
            """, user)
            
            if doc.warehouse in user_warehouses:
                return True
            
            return False
        elif ptype == "delete":
            # 余料用户不能删除记录
            return False
        else:
            return False
    
    # 其他角色只能查看自己创建的记录
    if ptype == "read":
        return doc.owner == user
    else:
        return False